import { readFile } from 'fs';
import { NORMALIZE_MAP } from './lib/normalize-map.js';
import { AudioPlayer } from "./lib/audio-player.js";

export class ControlCenter {
    constructor(music = '小星星', instrument = 'piano') {
        this.music = music;
        this.instrument = instrument;
        this.cur = 0;
        this.toneList = [];
        this.normalizeMap = NORMALIZE_MAP[instrument] || NORMALIZE_MAP['piano'];
        this.player = new AudioPlayer();
    }

    load() {
        return new Promise((resolve, reject) => {
            console.log('loading...');
            readFile(`./source/music/${this.music}.txt`, {}, (err, data) => {
                if (err) {
                    console.log(`当前曲库不存在: “${this.music}”, 请补充`);
                    reject(err);
                }
                this.toneList = 
                    data
                        .toString()
                        .replaceAll(/[\n\r]/g, ' ')
                        .replaceAll(/\s+/g, ' ')
                        .toLowerCase()
                        .split(' ')
                        .map(i => {
                            if (this.normalizeMap[i] !== undefined) {
                                return this.normalizeMap[i];
                            }
                            return i;
                        });
                console.log('ready!');
                console.log(`music: ${this.music}`);
                console.log(`musical instrument: ${this.instrument}`);
                resolve(true);
            });
        });
    }

    next() {
        const tone = this.toneList[this.cur++];
        console.log(tone);
        if (!tone) {
            return true;
        }
        this.player.play(`./source/tones/${this.instrument}/${tone}.mp3`);
        return this.cur >= this.toneList.length;
    }

    reset() {
        this.cur = 0;
    }
}